<?php
/**
 * customerID, loginID, password, firstName, lastName, email, referredSource, preferLanguageID, address, city, state, zipcode, phone
 */

/**
 * This is the model class for table "tbl_Customer".
 *
 * The followings are the available columns in table 'tbl_Customer':
 * @property integer $customerID
 * @property string $loginID
 * @property string $password
 * @property string $agentCode
 * @property string $firstName
 * @property string $lastName
 * @property string $email
 * @property integer $gender
 * @property string $address
 * @property string $address2
 * @property string $city
 * @property string $stateID
 * @property string $zipCode
 * @property string $StatementAddress
 * @property string $StatementCity
 * @property string $StatementZipcode
 * @property string $StatementState
 * @property string $phone
 * @property string $phone2
 * @property string $phone3
 * @property integer $referredSource
 * @property string $createdDate
 * @property string $lastLogonDate
 * @property string $modifiedDate
 * @property integer $securityQuestionID
 * @property string $securityAnswer
 * @property integer $preferLanguageID
 * @property string $isPromotion
 * @property string $SaveNote
 * @property string $AdvertiseReferral
 * @property string $Alert
 * @property string $TempPassword
 * @property string $TimePassword
 * @property string $TimePassword
 * @property string $subscriberID
 * The followings are the available model relations:
 * @property TblCustomerCSIRelation[] $tblCustomerCSIRelations
 */

class TblCustomer extends CActiveRecord
{
	public $areacode;
	public $prefixcode;
	public $phonenumber;
	public $password_repeat;
	
	private $orcCustomer = NULL;

	/**
	 * Before validate
	 * @see framework/base/CModel::beforeValidate()
	 */
	protected function beforeValidate()
	{
		if($this->isNewRecord)
		{
			$this->createdDate=$this->modifiedDate= date('Y-m-d');
		}
		else
		{
			$this->modifiedDate=date('Y-m-d');
		}

		return parent::beforeValidate();
	}
	
	protected function beforeSave()
	{
		$this->password_repeat = CGlobal::encrypt($this->password);
		$this->password = CGlobal::encrypt($this->password);
		return parent::beforeSave();
	}

	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return TblCustomer the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'tbl_Customer';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
		array('referredSource, preferLanguageID', 'numerical', 'integerOnly'=>true),
		array('loginID, email', 'length', 'max'=>150),
		array('password,', 'length', 'max'=>50),
		array('firstName, lastName, ', 'length', 'max'=>50),
		
		array('zipCode, ', 'length', 'max'=>12),
		array('createdDate, lastLogonDate, modifiedDate, ', 'safe'),
		// The following rule is used by search().
		// Please remove those attributes that should not be searched.
		array('customerID, loginID, password, firstName, lastName, email, address, city, stateID, zipCode, referredSource, createdDate, lastLogonDate, modifiedDate, preferLanguageID, ', 'safe', 'on'=>'search'),
		array('loginID, password, ', 'required'),
		array('email','email'),
		array('password', 'compare'),
		//array('loginID, email ', 'unique'),
		array('areacode, prefixcode, phonenumber', 'requiredPhone', 'areacode', 'prefixcode', 'phonenumber'),
		array('areacode, prefixcode, phonenumber', 'uniquePhone', 'areacode', 'prefixcode', 'phonenumber'),
		array('password_repeat, areacode, prefixcode, phonenumber, customerID, address, city, stateID', 'safe'),
			
		);
	}



	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'customerID'	   => 'Customer'		,
			'loginID'   	   => 'Login'   		,
			'password'  	   => 'Password'		,
			'firstName' 	   => 'First Name'  	,
			'lastName'  	   => 'Last Name'   	,
			'email' 		   => 'Email'   		,	
			'address'   	   => 'Address' 		,
			'city'  		   => 'City'			,
			'stateID'   	   => 'State'   		,
			'zipCode'   	   => 'Zip Code'		,
			'referredSource'   => 'Referred Source' ,
			'createdDate'      => 'Created Date'	,
			'lastLogonDate'    => 'Last Logon Date' ,
			'modifiedDate'     => 'Modified Date'   ,
			'preferLanguageID' => 'Prefer Language' ,
		);
	}


	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('customerID',$this->customerID);
		$criteria->compare('loginID',$this->loginID,true);
		$criteria->compare('password',$this->password,true);
		$criteria->compare('agentCode',$this->agentCode,true);
		$criteria->compare('firstName',$this->firstName,true);
		$criteria->compare('lastName',$this->lastName,true);
		$criteria->compare('email',$this->email,true);
		$criteria->compare('address',$this->address,true);
		$criteria->compare('city',$this->city,true);
		$criteria->compare('stateID',$this->stateID,true);
		$criteria->compare('zipCode',$this->zipCode,true);
		
		$criteria->compare('referredSource',$this->referredSource);
		$criteria->compare('createdDate',$this->createdDate,true);
		$criteria->compare('lastLogonDate',$this->lastLogonDate,true);
		$criteria->compare('modifiedDate',$this->modifiedDate,true);
		
		$criteria->compare('preferLanguageID',$this->preferLanguageID);


		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	/**
	 * Kiêm tra phone is unique
	 *
	 * @return boolean Error or Not
	 */
	public function requiredPhone($attribute, $params) 
	{
		if(!$this->hasErrors('Phone Number'))
		{
			$valid = true;
			foreach($params as $index => $p)
			{
				if($this->$p === '')
				{
					$valid = false;
					break;
				}
			}

			if ($valid === false)
			$this->addError( 'Phone Number', 'Phone Number can not be blank' );
		}
	}

	/**
	 * Unique number.
	 *
	 * @return returnType returnDescription
	 */
	public function uniquePhone($attribute, $params) {
		if(!$this->hasErrors('Phone Unique'))
		{
			$valid = true;
			$phone = '';
			foreach($params as $i => $p)
				$phone .= $this->$p;
				
				
			if(TblCustomerCSIRelation::isPhoneExists($phone))
			{
				$valid = false;
			}
			
			
			if($valid == false)
			{
				if(!$this->hasErrors('Phone Unique'))
					$this->addError( 'Phone Unique', 'Phone Number must be unique' );
			}
				
		}
	}

	

	//	public function save($runValidation=true,$attributes=null)
	//	{
	//		$transaction = $this->dbConnection->beginTransaction();
	//		$isValid = false;
	//		try
	//		{
	//			parent::save($runValidation,$attributes);
	//			insertAniNumber();
	//			$transaction->commit();
	//
	//			$isValid = true;
	//		}
	//		catch(Exception $e)
	//		{
	//			$transaction->rollBack();
	//			$isValid = false;
	//		}
	//
	//		return $isValid;
	//	}

	/**
	 * add ani number on sqlserver
	 *
	 * @return returnType returnDescription
	 */
	public function addAniNumber($subscriber_id) {

		$db = Yii::app()->db;
		$sql = "INSERT INTO tbl_CustomerCSIRelation (customerID,csiAccount, aniPhoneNumber, Is_DisableView) VALUES (:customerID, :csiAccount, :aniPhoneNumber, :Is_DisableView)";
	  
		$command = $db->createCommand($sql);
		
		$command->bindValue(':customerID', $this->customerID);
		$command->bindValue(':csiAccount', $subscriber_id);
		$command->bindValue(':aniPhoneNumber', $this->areacode.$this->prefixcode.$this->phonenumber, PDO::PARAM_STR);
		$command->bindValue(':Is_DisableView', True, PDO::PARAM_BOOL);
	  
		$valid = $command->execute();
		if($valid === false)
		{
			$this->addError('addANI', 'Save ANI Phone Number fail!');
		}
	  
		return $valid;
	}

	/**
	 * Lấy customer trên orc database.
	 *
	 * @return orcCustomer Customer Object
	 */
	public function getOrcCustomer() 
	{

	    if($this->orcCustomer === NULL)
	    {
	    	$this->orcCustomer = new OrcCustomer(trim($this->subscriberID));
	    }
	    
	    //var_dump($this->orcCustomer); die;
	    return $this->orcCustomer;
	}
	
	
	/**
	 * Get all number phone of this subscriber.
	 *
	 * @return ArrayObject array phone number object
	 */
	public function getPhones() {
	    $sql = "select aniPhoneNumber from tbl_CustomerCSIRelation where customerID = :customerID";
	    $command = Yii::app()->db->createCommand($sql);
		
		$command->bindValue(':customerID', $this->customerID, PDO::PARAM_INT);
				
		$listNumber = $command->queryAll();
		
		return $listNumber;
	}
}